<?php
require('header.php');
require('paginator.class.php');
requireAuth();

$facebook = new Facebook($fbconfig);
$fbUserId = $facebook->getUser();
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
?>
		<script>
		$(function() {
			$( ".datepicker" ).datepicker();
		});
		$(document).ready(function(){
			$('#btn-save-template').click(function(){
				$('.modal-body').html('');
				var url = $('#url').val(), msg = $('#message').val(), groups = $('#groups').val(), sdate = $('#sdate').val() + ' ' + $('#shour').val();
				var interval = $('#interval').val();
				var btn = $(this);
				if(groups == null){
					$('#groups').focus();
					return false;
				}
				if(url == '' && msg == ''){
					$('#url').focus();
					return false;
				}
				var templateName = prompt('Enter template name:');
				if(templateName != '' && templateName != 'null'){
					$.ajax({
						url: '<?php echo route('ajax') ?>',
						dataType: 'json',
						type: 'POST',
						data: {act:'save-template',from:'BULKGROUP',url:url,msg:msg,targets:groups,interval:interval,name:templateName},
						success: function(rs){
							if(typeof rs.result != 'undefined' && rs.result == 1){
								alert('Template saved successful.');
							}
							else{
								alert("Failed to save template\n" + rs);
							}
						},
						error: function(xhr, status, err){
							alert("Failed to save template\n" + xhr.responseText);
						}
					});
				}
			});
			$('#load-selected-template').live('click', function(){
				var tid = $('input.tempitem:checked').val();
				
				if(tid != ''){
					$.ajax({
						url: '<?php echo route('ajax') ?>',
						dataType: 'json',
						type: 'POST',
						data: {act:'load-template',from:'BULKGROUP', tid:tid},
						success: function(rs){
							if(typeof rs.result != 'undefined'){
								for(i in rs.result){
									$('#url').val(rs.result[i].s_post_url);
									$('#message').val(rs.result[i].s_post_message);
									$('#interval').val(rs.result[i].s_interval);
									if(rs.result[i].s_target != null){
										for(x in rs.result[i].s_target){
											$('#groups option[value="' + rs.result[i].s_target[x] + '"]').prop('selected', true);
										}
									}
								}
								$('#myModal').modal('hide');

							}
						},
						error: function(xhr, status, err){
							alert("Failed to load template\n" + xhr.responseText);
						}
					});
				}
				
			});
			$('#btn-load-template').click(function(){
				btn = $(this);
				btn.button('loading');
				$.ajax({
					url: '<?php echo route('ajax') ?>',
					dataType: 'json',
					type: 'POST',
					data: {act:'load-template',from:'BULKGROUP'},
					success: function(rs){
						clearModal();
						if(typeof rs.result != 'undefined'){
							templateItem = '';
							console.log(rs.result);
							for(i in rs.result){
								templateItem += '<li class="list-group-item" id="tpl_' + rs.result[i].id + '"><input id="user_opt_' + rs.result[i].id + '" value="' + rs.result[i].id + '" type="radio" name="tempitem" class="tempitem"> <label for="user_opt_' + rs.result[i].id + '">' + rs.result[i].s_name + ' <small class="text-muted"><i>('+ rs.result[i].s_post_created_at + ')<i></small></label><div class="pull-right"><a title="Remove this template" href="javascript:removeTemplate(' + rs.result[i].id + ')" class="remove-template" data-id="' + rs.result[i].id + '"><span class="glyphicon glyphicon-remove"> </span></a></div></li>';
							}
							$('.modal-body').append('<ul class="list-group user-list">' + templateItem + '</ul>');
							$('.modal-footer').append('<button type="button" class="btn btn-info" id="load-selected-template">Load selected template</button>');
							$('.modal-title').html('Saved templates');
							$('#myModal').modal();
						}
						else{
							alert("Failed to load template\n" + rs);
						}
						btn.button('reset');
					},
					error: function(xhr, status, err){
						alert("Failed to load template\n" + xhr.responseText);
						btn.button('reset');
					}
				});
			});

			$('#btn-save').click(function(){
				$('.modal-body').html('');
				var url = $('#url').val(), msg = $('#message').val(), groups = $('#groups').val();
				var btn = $(this);
				if(groups == null){
					$('#groups').focus();
					return false;
				}
				if(url == '' && msg == ''){
					$('#url').focus();
					return false;
				}
				btn.button('loading');
				$('.modal-body').html('<img src="/images/loading.gif" /> Sending to Facebook');
				//$('#btn-save').html('Submitting...');
				$.ajax({
					url: '<?php echo route('group-bulk-publish') ?>',
					dataType: 'json',
					type: 'POST',
					data: {url:url,msg:msg,groups:groups},
					success: function(rs){
						if(typeof rs != 'undefined' && rs.length > 0 && typeof rs.error == 'undefined'){
							var fbdata = '<p class="text-success">Posts submitted, click on IDs below to view on Facebook.</p>';
							for(i = 0; i < rs.length; i++){
								if(rs[i] != null){
									fbdata += '<p><a href="http://facebook.com/'+rs[i]+'" target="_blank">'+rs[i]+'</a></p>';
								}
								else{
									fbdata += '<p>FAILED</p>';
								}
							}
							$('.modal-body').html(fbdata);
						}
						else{
							$('.modal-body').html('<p class="text-error">Error when posting data.</p><pre>' + rs.msg + '</pre>');
						}
						btn.button('reset');
					},
					error: function(xhr, status, err){
						btn.button('reset');
						alert("Error when posting data\n" + xhr.responseText);
					}
				});

			});

			// RSS button
			$('#btn-rss').click(function(){
				$('.modal-body').html('');
				$('.modal-title').html('RSS grabber');

				$('.modal-body').append($('#frm-rss').clone()).html();
				$('#frm-rss').show();
			});
			$('.page-reload').click(function(){
				// location.href=location.href;
			});

			$('#btn-grab').live('click', function(){
				$('#rss-urls').val('');
				var rssUrl = $('#rss-url').val(), rssLimit = $('#rss-limit').val(), btn = $(this);
				if(rssUrl != ''){
					btn.button('loading');
					$('.data-table').remove();
					// $('.modal-body').append('<img src="/images/loading.gif" /> Grabbing URLs from RSS..');
					// $('#btn-save').html('Submitting...');
					$.ajax({
						url: '<?php echo route('ajax') ?>',
						dataType: 'json',
						type: 'POST',
						data: {act:'rss-grabber',url:rssUrl,limit:rssLimit},
						success: function(rs){
							if(typeof rs != 'undefined' && rs.length > 0){
								var html = '<hr class="data-table" /><p><div class="form-group data-table"><button type="button" class="btn btn-success btn-uselist btn-sm" data-dismiss="modal"><span class="glyphicon glyphicon-ok-circle"> </span>  Use selected URLs</button></div><p><div class="data-table" style="border: solid 1px #ccc; padding: 5px;"><table class="table table-striped">';
								var newLine = "";
								for(index in rs){
									if(index < rs.length - 1){
										newLine = "\n";
									}
									else{
										newLine = '';
									}
									html += '<tr><td><input type="checkbox" value="' + rs[index].link + '" name="url-items" class="url-items" checked></td><td><a href="' + rs[index].link + '" target="_blank"><p class="text-primary">' + rs[index].title + '</p></a><p class="text-muted"><small>' + rs[index].link + '<small></p></td></tr>';
									$('#rss-urls').val($('#rss-urls').val() + rs[index].link + newLine);
								}
								html += '</table></div><p><div class="form-group data-table"><button type="button" class="btn btn-success btn-uselist btn-sm" data-dismiss="modal"><span class="glyphicon glyphicon-ok-circle"> </span>  Use selected URLs</button></div><p>';

								$('.modal-body').append(html);
							}
							else{
								alert('Error when grabbing RSS');
							}
							btn.button('reset');
						},
						error: function(xhr, status, err){
						btn.button('reset');
							alert("Error when grabbing RSS\n" + xhr.responseText);
						}
					});

				}
			});
			$('.btn-uselist').live('click', function(){
				$('#url').val($('#rss-urls').val());
			});
			$('.url-items').live('click', function(){
				removable = $(this).val();
				currentList = $('#rss-urls').val();
				if($(this).is(':checked')){
					$('#rss-urls').val(currentList + "\n" + removable);
				}
				else{
					newList = currentList.replace(removable + "\n", '');
					newList = newList.replace(removable, '');
					$('#rss-urls').val(newList);
				}
			});
		});
		</script>
			<div class="row">
				<?php include('includes/listgrouppost.php') ?>
				<div class="col-md-5">
					<div class="well">
						<div class="panel panel-default">
						  <!-- Default panel contents -->
						  <div class="panel-heading"><h4><span class="glyphicon glyphicon-flash"></span> Bulk add schedule post <button type="button" data-backdrop="static" data-keyboard="false" id="btn-rss" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#myModal"><span class="glyphicon glyphicon-download"></span> Import from RSS</button></h4>
						  		
						  </div>
						  <!-- Table -->
						  <div class="container-fluid" style="margin:10px 0;">
							  <form class="form-horizontal" role="form">
							  	<div class="form-group">
								    <label for="groups" class="col-sm-4 control-label">Select groups</label>
								    <div class="col-sm-8">
								      <select name="groups" class="form-control" id="groups" multiple style="max-width: 400px;">
								      	<?php
								      	echo getOptGroup();
								      	?>
								      </select>
								    </div>
								</div>
								<hr />

							  	<div class="form-group">
								    <label for="url" class="col-sm-4 control-label">Link</label>
								    <div class="col-sm-8">
								      <textarea class="form-control" name="url" id="url" rows="2" placeholder="one URL per line"></textarea>
								    </div>
								</div>
							  	<div class="form-group">
								    <label for="message" class="col-sm-4 control-label">Message</label>
								    <div class="col-sm-8">
								      <textarea class="form-control" name="message" id="message" placeholder="one message per line. If you don't want show message for some URLs, please enter 'NULL'" rows="2"></textarea>
								    </div>
								</div>

							  <div class="form-group">
								    <div class="col-sm-offset-4 col-sm-8">
								      <button type="button" data-backdrop="static" data-keyboard="false" id="btn-save" class="btn btn-primary" data-toggle="modal" data-target="#myModal"><span class="glyphicon glyphicon-flash"></span> Submit</button>
								      
								      <button title="Save this post template" type="button" id="btn-save-template" class="btn btn-default" ><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>

								      <button type="button" id="btn-load-template" class="btn btn-default" title="Load from saved post templates"><span class="glyphicon glyphicon-download-alt"></span> Load</button>
								    </div>
								  </div>

							  </form>
							  
							</div>
						</div>
					</div>
				</div>

				<div class="modal fade" id="myModal">
				  <div class="modal-dialog">
				    <div class="modal-content">
				      <div class="modal-header">
				        <button type="button" class="close page-reload" data-dismiss="modal" aria-hidden="true">&times;</button>
				        <h4 class="modal-title">Result</h4>
				      </div>
				      <div class="modal-body">
				        
				      </div>
				      <div class="modal-footer">
				        <button type="button" class="btn btn-default page-reload" data-dismiss="modal">Close</button>
				      </div>
				    </div><!-- /.modal-content -->
				  </div><!-- /.modal-dialog -->
				</div><!-- /.modal -->
				<!-- RSS parser  form -->
				<form role="form" id="frm-rss" style="display: none;">
					<div class="form-group">
					    <label for="rss-url">RSS url:</label>
					    <input class="form-control" name="rss-url" id="rss-url" placeholder="URL of RSS feed"></textarea>
					</div>
					<div class="form-group">
					    <label for="rss-limit">Number of URL to grab</label>
					    <input class="form-control" name="rss-limit" id="rss-limit" style="width: 60px; font-weight: bold;" value="10"></textarea>
					</div>
					<div class="form-group">
						<div>
						  <button type="button" id="btn-grab" class="btn btn-success"><span class="glyphicon glyphicon-download"></span> Grab</button>
						</div>
					</div>

				</form>
				<textarea id="rss-urls" style="display: none;"></textarea>
				<!--/ RSS parser  form -->
			</div>
<?php require('footer.php'); ?>